import React from 'react'
import { BookOpen, Filter, Search } from 'lucide-react'
import { motion } from 'framer-motion'
import { Link } from 'react-router-dom'
import { useStore } from '../stores/appStore'
import { cn } from '../utils/cn'

const Books: React.FC = () => {
  // const { books } = useStore()

  // 模拟分类数据
  const categories = [
    { id: 'all', name: '全部', icon: '📚' },
    { id: 'emotion', name: '情感教育', icon: '❤️' },
    { id: 'cognition', name: '认知启蒙', icon: '🧠' },
    { id: 'habit', name: '习惯养成', icon: '🌱' },
    { id: 'family', name: '亲情关系', icon: '👨‍👩‍👧‍👦' },
    { id: 'nature', name: '自然科普', icon: '🌿' },
    { id: 'story', name: '童话故事', icon: '👑' },
    { id: 'art', name: '艺术启蒙', icon: '🎨' },
  ]

  const ageRanges = [
    { id: 'all', range: [0, 12], label: '全部年龄' },
    { id: '0-2', range: [0, 2], label: '0-2岁' },
    { id: '2-4', range: [2, 4], label: '2-4岁' },
    { id: '4-6', range: [4, 6], label: '4-6岁' },
    { id: '6-8', range: [6, 8], label: '6-8岁' },
    { id: '8-12', range: [8, 12], label: '8-12岁' },
  ]

  const [selectedCategory, setSelectedCategory] = React.useState('all')
  const [selectedAgeRange, setSelectedAgeRange] = React.useState('all')
  const [searchQuery, setSearchQuery] = React.useState('')
  const [sortBy, setSortBy] = React.useState('rating')

  // 模拟绘本数据
  const mockBooks = [
    {
      id: '1',
      title: '小熊宝宝绘本',
      author: '佐佐木洋子',
      cover: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=cute%20little%20bear%20character%20in%20warm%20children%20book%20illustration%20style%20soft%20colors%20gentle%20lighting&image_size=portrait_4_3',
      description: '培养宝宝良好习惯的温馨绘本',
      ageRange: [0, 3] as [number, number],
      category: 'habit',
      tags: ['习惯', '动物', '温馨'],
      rating: 4.8,
      price: 28.8,
      isFree: false,
      pages: 24
    },
    {
      id: '2',
      title: '彩虹色的花',
      author: '麦克·格雷涅茨',
      cover: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=colorful%20rainbow%20flower%20in%20children%20book%20illustration%20style%20bright%20colors%20whimsical%20art%20style&image_size=portrait_4_3',
      description: '关于分享与友爱的美丽故事',
      ageRange: [3, 6] as [number, number],
      category: 'emotion',
      tags: ['分享', '友爱', '自然'],
      rating: 4.9,
      price: 0,
      isFree: true,
      pages: 32
    },
    {
      id: '3',
      title: '我爸爸',
      author: '安东尼·布朗',
      cover: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=father%20and%20child%20illustration%20in%20children%20book%20style%20warm%20family%20moment%20soft%20colors&image_size=portrait_4_3',
      description: '表达对爸爸深深的爱',
      ageRange: [2, 5] as [number, number],
      category: 'family',
      tags: ['爸爸', '亲情', '温馨'],
      rating: 4.7,
      price: 32.0,
      isFree: false,
      pages: 28
    },
    {
      id: '4',
      title: '好饿的毛毛虫',
      author: '艾瑞·卡尔',
      cover: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=cute%20caterpillar%20in%20children%20book%20illustration%20style%20bright%20colors%20whimsical%20art&image_size=portrait_4_3',
      description: '经典洞洞书，认识数字和食物',
      ageRange: [1, 4] as [number, number],
      category: 'cognition',
      tags: ['数字', '食物', '洞洞书'],
      rating: 4.9,
      price: 35.0,
      isFree: false,
      pages: 26
    },
    {
      id: '5',
      title: '猜猜我有多爱你',
      author: '山姆·麦克布雷尼',
      cover: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=loving%20rabbits%20in%20children%20book%20illustration%20style%20soft%20pastel%20colors%20tender%20moment&image_size=portrait_4_3',
      description: '关于爱的表达的经典绘本',
      ageRange: [2, 6] as [number, number],
      category: 'emotion',
      tags: ['爱', '兔子', '温馨'],
      rating: 4.8,
      price: 29.9,
      isFree: false,
      pages: 30
    },
    {
      id: '6',
      title: '小蓝和小黄',
      author: '李欧·李奥尼',
      cover: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=blue%20and%20yellow%20circles%20children%20book%20illustration%20simple%20geometric%20shapes%20colorful&image_size=portrait_4_3',
      description: '关于友谊和颜色的故事',
      ageRange: [2, 5] as [number, number],
      category: 'emotion',
      tags: ['友谊', '颜色', '创意'],
      rating: 4.6,
      price: 0,
      isFree: true,
      pages: 36
    }
  ]

  const filteredBooks = mockBooks.filter(book => {
    const matchesCategory = selectedCategory === 'all' || book.category === selectedCategory
    const matchesAge = selectedAgeRange === 'all' || 
      (book.ageRange[0] >= ageRanges.find(range => range.id === selectedAgeRange)?.range[0] &&
       book.ageRange[1] <= ageRanges.find(range => range.id === selectedAgeRange)?.range[1])
    const matchesSearch = searchQuery === '' || 
      book.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      book.author.toLowerCase().includes(searchQuery.toLowerCase()) ||
      book.tags.some(tag => tag.toLowerCase().includes(searchQuery.toLowerCase()))
    
    return matchesCategory && matchesAge && matchesSearch
  }).sort((a, b) => {
    if (sortBy === 'rating') return b.rating - a.rating
    if (sortBy === 'price') return a.price - b.price
    if (sortBy === 'newest') return b.id.localeCompare(a.id)
    return 0
  })

  const BookCard: React.FC<{ book: any }> = ({ book }: { book: any }) => {
    return (
      <Link to={`/books/${book.id}`}>
        <motion.div
          whileHover={{ scale: 1.03 }}
          whileTap={{ scale: 0.98 }}
          className="bg-white rounded-2xl shadow-lg hover:shadow-xl transition-all duration-300 overflow-hidden group"
        >
          <div className="aspect-[3/4] relative overflow-hidden">
            <img
              src={book.cover}
              alt={book.title}
              className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-300"
            />
            {book.isFree && (
              <div className="absolute top-2 right-2 bg-leaf-500 text-white px-2 py-1 rounded-full text-xs font-bold">
                免费
              </div>
            )}
            <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/60 to-transparent p-3">
              <div className="flex items-center justify-between">
                <span className="text-white text-xs font-medium">
                  {book.ageRange[0]}-{book.ageRange[1]}岁
                </span>
                <div className="flex items-center space-x-1">
                  <svg className="w-3 h-3 text-yellow-400 fill-current" viewBox="0 0 20 20">
                    <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
                  </svg>
                  <span className="text-white text-xs">{book.rating}</span>
                </div>
              </div>
            </div>
          </div>
          <div className="p-4">
            <h3 className="font-bold text-gray-800 text-base mb-2 line-clamp-1">{book.title}</h3>
            <p className="text-sm text-gray-600 mb-3 line-clamp-2">{book.description}</p>
            <p className="text-sm text-gray-500 mb-3">作者：{book.author}</p>
            <div className="flex flex-wrap gap-1 mb-3">
              {book.tags.map((tag: string) => (
                <span key={tag} className="text-xs bg-primary-50 text-primary-600 px-2 py-1 rounded-full">
                  {tag}
                </span>
              ))}
            </div>
            <div className="flex items-center justify-between">
              <span className="text-lg font-bold text-primary-600">
                {book.isFree ? '免费' : `¥${book.price}`}
              </span>
              <span className="text-sm text-gray-500">{book.pages}页</span>
            </div>
          </div>
        </motion.div>
      </Link>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="text-center">
        <h1 className="text-3xl font-bold text-gray-800 mb-2 flex items-center justify-center">
          <BookOpen className="w-8 h-8 text-primary-500 mr-3" />
          绘本馆
        </h1>
        <p className="text-gray-600">发现最适合孩子的优质绘本</p>
      </div>

      {/* 搜索栏 */}
      <div className="bg-white rounded-2xl p-4 shadow-lg">
        <div className="relative">
          <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="搜索绘本、作者或关键词..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full pl-12 pr-4 py-3 border-2 border-gray-200 rounded-2xl focus:border-primary-300 focus:outline-none transition-colors"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
        {/* 筛选侧边栏 */}
        <div className="lg:col-span-1">
          <div className="bg-white rounded-2xl p-6 shadow-lg sticky top-24">
            <div className="flex items-center mb-4">
              <Filter className="w-5 h-5 text-primary-500 mr-2" />
              <h3 className="text-lg font-bold text-gray-800">筛选条件</h3>
            </div>

            {/* 分类筛选 */}
            <div className="mb-6">
              <h4 className="font-medium text-gray-700 mb-3">绘本分类</h4>
              <div className="space-y-2">
                {categories.map((category) => (
                  <button
                    key={category.id}
                    onClick={() => setSelectedCategory(category.id)}
                    className={cn(
                      "w-full text-left px-3 py-2 rounded-xl transition-colors flex items-center space-x-2",
                      selectedCategory === category.id
                        ? "bg-primary-100 text-primary-700 border-2 border-primary-200"
                        : "bg-gray-50 text-gray-600 hover:bg-gray-100"
                    )}
                  >
                    <span>{category.icon}</span>
                    <span className="text-sm">{category.name}</span>
                  </button>
                ))}
              </div>
            </div>

            {/* 年龄筛选 */}
            <div className="mb-6">
              <h4 className="font-medium text-gray-700 mb-3">适合年龄</h4>
              <div className="space-y-2">
                {ageRanges.map((range) => (
                  <button
                    key={range.id}
                    onClick={() => setSelectedAgeRange(range.id)}
                    className={cn(
                      "w-full text-left px-3 py-2 rounded-xl transition-colors text-sm",
                      selectedAgeRange === range.id
                        ? "bg-primary-100 text-primary-700 border-2 border-primary-200"
                        : "bg-gray-50 text-gray-600 hover:bg-gray-100"
                    )}
                  >
                    {range.label}
                  </button>
                ))}
              </div>
            </div>

            {/* 排序方式 */}
            <div>
              <h4 className="font-medium text-gray-700 mb-3">排序方式</h4>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value)}
                className="w-full px-3 py-2 border-2 border-gray-200 rounded-xl focus:border-primary-300 focus:outline-none transition-colors"
              >
                <option value="rating">评分最高</option>
                <option value="price">价格最低</option>
                <option value="newest">最新上架</option>
              </select>
            </div>
          </div>
        </div>

        {/* 绘本列表 */}
        <div className="lg:col-span-3">
          <div className="mb-4 flex items-center justify-between">
            <p className="text-gray-600">
              共找到 <span className="font-bold text-primary-600">{filteredBooks.length}</span> 本绘本
            </p>
          </div>

          {filteredBooks.length === 0 ? (
            <div className="bg-white rounded-2xl p-12 text-center shadow-lg">
              <BookOpen className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <h3 className="text-lg font-medium text-gray-600 mb-2">暂无相关绘本</h3>
              <p className="text-gray-500">试试调整筛选条件或搜索关键词</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
              {filteredBooks.map((book) => (
                <BookCard key={book.id} book={book} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default Books